package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Dish;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnOverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList){
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            Double turnover = orderMapper.statisticsOrderAmount(Orders.COMPLETED,min,max);
            if (turnover == null){
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }
        String dateListStr = StringUtils.join(dateList, ",");
        String turnoverListStr = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO.builder()
                .dateList(dateListStr)
                .turnoverList(turnoverListStr).build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList){
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            Integer dayUser = userMapper.statisticsUserNum(min,max);
            Integer totalUser = userMapper.statisticsUserNum(null,max);
            if (dayUser == null){
                dayUser = 0;
            }
            newUserList.add(dayUser);
            totalUserList.add(totalUser);
        }
        String dateListStr = StringUtils.join(dateList, ",");
        String newUserListStr = StringUtils.join(newUserList, ",");
        String totalUserListStr = StringUtils.join(totalUserList, ",");

        return UserReportVO.builder()
                .dateList(dateListStr).newUserList(newUserListStr).totalUserList(totalUserListStr).build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        int totalOrderCount = 0;
        int validOrderCount = 0;
        double orderCompletionRate = 0.0;
        for (LocalDate date : dateList){
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            Integer orderCount = orderMapper.statisticsUserNum(null,min,max);
            orderCountList.add(orderCount);
            totalOrderCount+=orderCount;
            Integer validCount = orderMapper.statisticsUserNum(Orders.COMPLETED,min,max);
            validOrderList.add(validCount);
            validOrderCount+=validCount;
        }
        if (totalOrderCount == 0){
            orderCompletionRate = 0.0;
        }else {
            orderCompletionRate = (double) validOrderCount /totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime min = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime max = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO>  goodsSalesDTO=  orderMapper.statisticsSales(Orders.COMPLETED,min,max);
        List<String> goodsNameList = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> goodsNumberList = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(goodsNameList, ","))
                .numberList(StringUtils.join(goodsNumberList, ","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate min = LocalDate.now().minusDays(30);
        LocalDate max = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(min, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(max, LocalTime.MAX);

        BusinessDataVO businessDate = workspaceService.getBusinessDate(begin,end);
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template.xlsx");
        XSSFWorkbook workbook = null;
        try {
            if (resourceAsStream != null) {
                workbook = new XSSFWorkbook(resourceAsStream);
                XSSFSheet sheet = workbook.getSheet("Sheet1");
                sheet.getRow(1).getCell(1)
                        .setCellValue("时间："+min+"至"+max);
                XSSFRow row = sheet.getRow(3);
                row.getCell(2).setCellValue(businessDate.getTurnover());
                row.getCell(4).setCellValue(businessDate.getOrderCompletionRate());
                row.getCell(6).setCellValue(businessDate.getNewUsers());
                row = sheet.getRow(4);
                row.getCell(2).setCellValue(businessDate.getValidOrderCount());
                row.getCell(4).setCellValue(businessDate.getUnitPrice());
                int index=7;
                row = sheet.getRow(index);
                List<LocalDate> dateList = new ArrayList<>();
                while (!min.equals(max)){
                    dateList.add(min);
                    min = min.plusDays(1);
                }
                dateList.add(max);
                for (LocalDate date : dateList){
                    LocalDateTime dataBegin = LocalDateTime.of(date, LocalTime.MIN);
                    LocalDateTime dataEnd = LocalDateTime.of(date, LocalTime.MAX);
                    businessDate= workspaceService.getBusinessDate(dataBegin,dataEnd);
                    row.getCell(1).setCellValue(date.toString());
                    row.getCell(2).setCellValue(businessDate.getTurnover());
                    row.getCell(3).setCellValue(businessDate.getValidOrderCount());
                    row.getCell(4).setCellValue(businessDate.getOrderCompletionRate());
                    row.getCell(5).setCellValue(businessDate.getUnitPrice());
                    row.getCell(6).setCellValue(businessDate.getNewUsers());
                    row = sheet.getRow(++index);
//                    row = sheet.createRow(row.getRowNum()+1);
                }
                ServletOutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);

                outputStream.close();
                workbook.close();



            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
